<?php
$wind_in = 'sc';
require_once('global.php');
!$gp_allowsearch && Showmsg('search_group_right');
if ($groupid!=3 && $groupid!=4) {
	list($db_opensch,$db_schstart,$db_schend) = explode("\t",$db_opensch);
	if ($db_opensch && (($db_schstart>-1 && $t['hours']<$db_schstart) || ($db_schend>-1 && $t['hours']>=$db_schend))) {
		Showmsg('search_opensch');
	}
}
InitGP(array('keyword','newatc','authorid','digest','step','sch_area'));
$sch_area = (int)$sch_area;
$sch_area>0 && $gp_allowsearch!=2 && Showmsg('search_tpost');
if (isset($authorid) && (int)$authorid<1) {
	$errorname = Char_cv($authorid);
	Showmsg('user_not_exists');
}
if ($keyword) {
	$keyword = Char_cv(trim($keyword));
	$keyword && strlen($keyword)<3  && Showmsg('search_word_limit');
	$metakeyword = strip_tags($keyword);
	$subject = "$metakeyword - ";
	$db_metakeyword = str_replace('|',',',$metakeyword);
}
require_once(R_P.'require/header.php');

$forumadd = $fidout = $cmscache = $p_table = $f = $db_searchinfo = '';
($newatc || is_numeric($authorid) || $digest) && $step = 2;

require_once(D_P.'data/bbscache/forumcache.php');
$_SELECT = $step!=2 ? ',name,f_type' : ',forumadmin,fupadmin';
$checkdb = array();
$query = $db->query("SELECT fid,allowvisit,password$_SELECT FROM pw_forums WHERE type<>'category'");
while ($rt = $db->fetch_array($query)) {
	$allowvisit = (!$rt['allowvisit'] || $rt['allowvisit']!=str_replace(",$groupid,",'',$rt['allowvisit'])) ? true : false;
	if ($rt['f_type']=='hidden' && $allowvisit) {
		$forumadd .= "<option value=\"$rt[fid]\"> &nbsp;|- $rt[name]</option>";
	} elseif ($rt['password'] || !$allowvisit) {
		if ($step!=2) {
			$forumcache = preg_replace("/\<option value=\"$rt[fid]\"\>(.+?)\<\/option\>\\n/is",'',$forumcache);
		} else {
			$fidout .= ",'$rt[fid]'";
		}
	}
	if ($rt['forumadmin'] || $rt['fupadmin']) {
		$checkdb[$rt['fid']] = $rt['forumadmin'].$rt['fupadmin'];
	}
}
$fidout && $fidout = substr($fidout,1);
$_G['schtime']!='all' && !is_numeric($_G['schtime']) && $_G['schtime'] = 7776000;
if ($step!=2) {
	list($f,$db_searchinfo) = explode("\t",readover(D_P.'data/bbscache/info.txt'));
	$disable = $gp_allowsearch==1 ? 'disabled' : '';
	if ($gp_allowsearch==2) {
		$t_table = '';
		if ($db_plist) {
			$p_table = '<select name="ptable"><option value="0">posts</option>';
			$p_list = explode(',',$db_plist);
			foreach ($p_list as $value) {
				$p_table .= "<option value=\"$value\">posts$value</option>";
			}
			$p_table .= '</select>';
		}
		if ($db_tlist) {
			$t_list = unserialize($db_tlist);
			$t_table = '<select name="ttable">';
			foreach ($t_list as $key => $value) {
				$t_table .= "<option value=\"$key\">tmsgs$key</option>";
			}
			$t_table .= '<option value="0">tmsgs</option></select>';
		}
	}
	${'time_'.$_G['schtime']} = 'selected';
	require_once PrintEot('search');footer();
} else {
	require_once(D_P.'data/bbscache/forum_cache.php');
	@set_time_limit(0);
	$keyword_A = array();
	$schedid = '';
	InitGP(array('sid','seekfid','s_type','f_fid','c_fid','page','ptable'));
	$f_fid = (int)$f_fid;
	$c_fid = (int)$c_fid;
	!$seekfid && $seekfid = (empty($s_type) || $s_type=='all') ? 'all' : ($s_type=='forum' ? $f_fid : $c_fid);
	$admincheck = $total = 0;
	if ($seekfid!='all') {
		$seekfid = (int)$seekfid;
		if ($windid && strpos($checkdb[$seekfid],",$windid,")!==false) {
			$admincheck = 1;
		} elseif ($groupid!=5 && ($SYSTEM['tpctype'] || $SYSTEM['delatc'] || $SYSTEM['moveatc'] || $SYSTEM['copyatc'])) {
			$admincheck = 1;
		}
	}
	unset($checkdb,$s_type,$f_fid,$c_fid);
	$sid = (int)$sid;
	if ($sid>0) {
		@extract($db->get_one("SELECT sorderby,total,schedid FROM pw_schcache WHERE sid='$sid'"));
		$total = (int)$total;
		list($orderway,$asc) = explode('|',$sorderby);
		$orderby = "ORDER BY t.$orderway $asc";
	} else {
		$sch_area>2 && $sch_area = 2;
		InitGP(array('pwuser','sch_time','method','orderway','ttable'));
		$_POST && empty($keyword) && empty($pwuser) && $sch_time=='all' && Showmsg('no_condition');
		$method!='AND' && $method = 'OR';
		$schline = 'search|'.trim($keyword).'|'.trim($method).'|'.trim($sch_area).'|'.trim($seekfid).'|'.trim($pwuser).'|'.trim($authorid).'|'.trim($sch_time).'|'.trim($digest);
		$db_plist && $schline .= '|'.$ptable;
		$db_tlist && $schline .= '|'.$ttable;
		$schline = md5($schline.'|search');
		($orderway!='replies' || $orderway!='hits') && $orderway = 'lastpost';
		$asc!='ASC' && $asc = 'DESC';
		$sorderby = $orderway.'|'.$asc;
		$orderby = "ORDER BY t.$orderway $asc";
		if (!$authorid) {
			@extract($db->get_one("SELECT sid,schtime,total,schedid FROM pw_schcache WHERE schline='$schline' LIMIT 1"));
			if ($newatc && $timestamp-$schtime>1800) {
				$db->update("DELETE FROM pw_schcache WHERE sid='$sid'");
				$schedid = '';
			}
		}
		if (!$schedid) {
			$db_schwait = (int)$db_schwait;
			if (file_exists(D_P.'data/bbscache/schwait_cache.php')) {
				if ($timestamp-filemtime(D_P.'data/bbscache/schwait_cache.php')>$db_schwait) {
					P_unlink(D_P.'data/bbscache/schwait_cache.php');
				} else {
					Showmsg('search_wait');
				}
			}
			$db->update("DELETE FROM pw_schcache WHERE schtime<$timestamp-3600");
			if (($keyword || $pwuser || !is_numeric($authorid)) && $gp_searchtime!=0) {
				@extract($db->get_one("SELECT lasttime FROM pw_memberinfo WHERE uid='$winduid'"));
				if ($timestamp-$lasttime<$gp_searchtime) {
					Showmsg('search_limit');
				}
				$db->update("UPDATE pw_memberinfo SET lasttime='$timestamp' WHERE uid='$winduid'");
			}
			$sqlwhere = "t.ifcheck='1' ";
			if ($seekfid!='all') {
				if ($forum[$seekfid]['type']=='category') {
					Showmsg('search_cate');
				}
				if (strpos(",$fidout,",",'$seekfid',")===false) {
					$sqlwhere .= "AND t.fid='$seekfid'";
				} else {
					Showmsg('search_forum_right');
				}
			} elseif ($fidout) {
				$sqlwhere .= "AND t.fid NOT IN ($fidout)";
			}
			$distinct = '';
			$sqltable = 'pw_threads t';
			$tablepre = '';
			if ($gp_allowsearch==2 && $sch_area>0) {
				if ($sch_area==1) {
					$tlistdb = $db_tlist ? unserialize($db_tlist) : array();
					$pw_tmsgs = isset($tlistdb[$ttable]) ? "pw_tmsgs$ttable" : 'pw_tmsgs';
					$keyword && $sqltable .= " LEFT JOIN $pw_tmsgs tm ON tm.tid=t.tid";
					$tablepre = 'tm';
				} elseif ($sch_area==2) {
					$pw_posts = GetPtable($ptable);
					if ($db_plist && is_numeric($authorid)) {
						${'selected'.$ptable} = 'SELECTED';
						$p_table = "<select name=\"ptable\" onChange=\"window.location='search.php?authorid=$authorid&sch_area=2&ptable='+this.options[this.selectedIndex].value;\"><option value=\"0\">posts</option>";
						$p_list  = explode(',',$db_plist);
						foreach ($p_list as $value) {
							$p_table .= "<option value=\"$value\" ${'selected'.$value}>posts$value</option>";
						}
						$p_table .= "</select>";
					}
					$distinct = 'DISTINCT';
					$sqltable = "$pw_posts t";
					$sorderby = 'tid|'.$asc;
					$orderby  = "ORDER BY tid $asc";
					$tablepre = 't';
				}
			}
			if ($keyword) {
				$keywhere = '';
				$keyword = str_replace(array('%','_'),array('\%','\_'),trim($keyword));
				$keyword_A = explode('|',$keyword);
				foreach ($keyword_A as $value) {
					if ($value) {
						$value = addslashes($value);
						$keywhere .= $method;
						if (!$sch_area) {
							$keywhere .= " t.subject LIKE '%$value%'";
						} elseif ($tablepre) {
							$keywhere .= " (t.subject LIKE '%$value%' OR $tablepre.content LIKE '%$value%')";
						}
					}
				}
				$keywhere && $keywhere = substr_replace($keywhere,'',0,3);
				!$keywhere && Showmsg('illegal_keyword');
				$sqlwhere .= " AND ($keywhere)";
			} elseif ($pwuser) {
				!str_replace('*','',$pwuser) && Showmsg('illegal_author');
				$uids = '';
				$pwuser = str_replace(array('%','_'),array('\%','\_'),addslashes(trim($pwuser)));
				$pwuser = str_replace('*','_',$pwuser);//noizyfeng
				$query = $db->query("SELECT uid FROM pw_members WHERE username LIKE '$pwuser'");
				while ($rt = $db->fetch_array($query)) {
					$uids .= ($uids ? ',' : '')."'$rt[uid]'";
				}
				!$uids && Showmsg('user_not_exists');
				$sqlwhere .= " AND t.authorid IN ($uids)";
			} elseif (is_numeric($authorid)) {
				$sqlwhere .= " AND t.authorid = '$authorid'";
			}
			$digest && $sch_area<2 && $sqlwhere .= " AND t.digest>0";
			if (!is_numeric($authorid) && (!$digest || $sch_time)) {
				if ($sch_time!='all') {
					!is_numeric($sch_time) && $sch_time = 86400;
					$_G['schtime']=='all' && $_G['schtime'] = 31536000;
					$sch_time>$_G['schtime'] && $sch_time = $_G['schtime'];
					$sqlwhere .= " AND t.postdate > $timestamp-$sch_time";
				} elseif ($_G['schtime']!='all') {
					$sqlwhere .= " AND t.postdate > $timestamp-$_G[schtime]";
				}
			}
			$limit = 'LIMIT 50';
			if (!$newatc) {
				!$db_maxresult && $db_maxresult = 500;
				$limit = "LIMIT $db_maxresult";
			}
			$schsql = " t.tid FROM $sqltable WHERE $sqlwhere $orderby";
			if (strpos($sqltable,'tm')===false) {
				$schsql = str_replace(array(' t.',' t ','(t.'),array(' ',' ','('),$schsql);
			}
			$query = $db->query("SELECT $distinct$schsql $limit");
			while ($rt = $db->fetch_array($query)) {
				$total++;
				$schedid .= ",$rt[tid]";
			}
			$db->free_result($query);
			if ($schedid) {
				$schedid = substr($schedid,1);
				if ((int)$authorid<1) {
					$db->update("INSERT INTO pw_schcache(sorderby,schline,schtime,total,schedid) VALUES ('$sorderby','$schline','$timestamp','$total','$schedid')");
					$sid = $db->insert_id();
					$db_schwait && writeover(D_P.'data/bbscache/schwait_cache.php','');
				}
			}
		}
	}
	if ($schedid) {
		$schdb = array();
		$pages = $addpage = $rawkeyword = $htmlurl = '';
		(int)$page<1 && $page = 1;
		$limit = 'LIMIT '.($page-1)*$db_perpage.",$db_perpage";
		if ($keyword) {
			$keyword_A = explode('|',$keyword);
			$rawkeyword = rawurlencode($keyword);
			$htmlurl = $addpage = "&keyword=$rawkeyword";
		}
		$sqlwhere = "tid IN ('".str_replace(',',"','",$schedid)."')";
		$fidout && $sqlwhere .= " AND fid NOT IN ($fidout)";
		$orderby = str_replace('t.','',$orderby);
		$query = $db->query("SELECT tid,fid,titlefont,author,authorid,subject,postdate,lastpost,lastposter,hits,replies,locked,special,anonymous FROM pw_threads WHERE $sqlwhere $orderby $limit");
		while ($rt = $db->fetch_array($query)) {
			if ($rt['anonymous'] && $rt['author']!=$windid) {
				if ($groupid!='3') continue;
				$rt['author'] = $db_anonymousname;
				$rt['authorid'] = 0;
			}
			if ($rt['titlefont']) {
				$titledetail = explode('~',$rt['titlefont']);
				if ($titledetail[0]) $rt['subject'] = "<font color=\"$titledetail[0]\">$rt[subject]</font>";
				if ($titledetail[1]) $rt['subject'] = "<b>$rt[subject]</b>";
				if ($titledetail[2]) $rt['subject'] = "<i>$rt[subject]</i>";
				if ($titledetail[3]) $rt['subject'] = "<u>$rt[subject]</u>";
			}
			foreach ($keyword_A as $value) {
				$value && $rt['subject'] = preg_replace('/(?<=[^\w=]|^)('.preg_quote($value,'/').')(?=[^\w=]|$)/si','<font color="red"><u>\\1</u></font>',$rt['subject']);
			}
			if ($rt['special']==1) {
				$rt['status'] = !$rt['locked'] ? 'vote' : 'votelock';
			} elseif ($rt['locked']>0) {
				$rt['status'] = $rt['locked']==1 ? 'topiclock' : 'topicclose';
			} else {
				$rt['status'] = $rt['replies']>=10 ? 'topichot' : 'topicnew';
			}
			$rt['forumname'] = $forum[$rt['fid']]['name'];
			$rt['postdate'] = get_date($rt['postdate'],"Y-m-d");
			$rt['lastpost'] = get_date($rt['lastpost']);
			$rt['lastposterraw'] = rawurlencode($rt['lastposter']);
			$schdb[] = $rt;
		}
		$db->free_result($query);
		if ($newatc && $total > 50) {
			$total = 50;
			$db->update("UPDATE pw_schcache SET total='50' WHERE sid='$sid'");
		}
		if ($total > $db_perpage) {
			if (!$sid) {
				$ptable && $addpage .= "&ptable=$ptable";
				$digest && $addpage .= "&digest=$digest";
			} else {
				$addpage .= "&sid=$sid";
			}
			$authorid && $addpage .= "&authorid=$authorid";
			$seekfid && $addpage .= "&seekfid=$seekfid";
			$sch_area && $addpage .= "&sch_area=$sch_area";
			require_once(R_P.'require/forum.php');
			$numofpage = ceil($total/$db_perpage);
			$pages = numofpage($total,$page,$numofpage,"search.php?step=2$addpage&");
		}
		require_once PrintEot('search');footer();
	} else {
		Showmsg('search_none');
	}
}
?>
